<?php namespace App\Repositories;

use Bosnadev\Repositories\Contracts\RepositoryInterface;
use Bosnadev\Repositories\Eloquent\Repository;

/**
 * Class SerialNumberRepository
 * @package App\Repositories
 */
class SerialNumberRepository extends _appRepository
{

    /**
     * @return string
     */
    public function model()
    {
        return 'App\Models\SerialNumber';
    }
     public function GetNumber($type=1,$length=3){
    	$file = fopen(storage_path('/a'.$type.'.txt'),"w+");
		 	while (!flock($file,LOCK_EX))
			 {
			 	;
			 }
		  flock($file,LOCK_UN);
		 
    	$this->applyCriteria();
    	$number=1;
      $result = $this->model->where('Type', '=', $type)->first();
      $date_time_val= date('Y-m-d');
      if(empty($result))
      {
      	$result=[
      	'Type'=>$type,
      	'DateTimeVal'=> $date_time_val,
      	 'Number'=>$number
      	];
      	$this->model->create($result);
      	 
      }else{
      	if($result->DateTimeVal==$date_time_val){
      			$result->Number+=1;
      			$number=$result->Number;
      		}else{
      	   $result->DateTimeVal=$date_time_val;
      	   $result->Number=$number;
      		} 
      	 
      		$this->model->where('ID', '=', $result->ID)->update(['Number'=>$result->Number,'DateTimeVal'=>$result->DateTimeVal]);
      	}
      	 fclose($file);
      return date('Ymd').str_pad($number,$length,'0',STR_PAD_LEFT);
    }
}